/**
 * 版权所有(C)，上海勾芒信息科技，2016，所有权利保留。
 * 
 * 项目名：	car-web
 * 文件名：	HandlerPost.java
 * 模块说明：	
 * 修改历史：
 * 2016年11月16日 - Debenson - 创建。
 */
package com.alex.wechat.core.handler;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.FatalBeanException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

import com.gomore.jeecg.common.Assert;

import me.chanjar.weixin.message.rule.WxMessageHandler;
import me.chanjar.weixin.message.rule.WxMessageRouter;
import me.chanjar.weixin.message.rule.WxMessageRouterRule;

/**
 * 微信Handler后处理器
 * 
 * @author Debenson
 * @since 0.1
 */
@Component(value = "WxHandlerPostProcessor")
public class WxHandlerPostProcessor implements BeanPostProcessor {
  private static final Logger logger = LoggerFactory.getLogger(WxHandlerPostProcessor.class);

  @Autowired
  private WxMessageRouter router;

  @Override
  public Object postProcessBeforeInitialization(Object bean, String beanName)
      throws BeansException {
    return bean;
  }

  @Override
  public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
    if (bean.getClass().isAnnotationPresent(WxHandler.class)) {
      if (!(bean instanceof WxMessageHandler)) {
        throw new FatalBeanException(
            "类" + bean.getClass().getName() + "没有实现" + WxMessageHandler.class.getName() + "接口");
      }

      register((WxMessageHandler) bean);
      if (logger.isInfoEnabled()) {
        logger.info("已注册微信事件处理器: class={}", bean.getClass().getName());
      }
    }
    return bean;
  }

  public void register(WxMessageHandler handler) {
    Assert.assertArgumentNotNull(handler, "handler");

    WxHandler anno = handler.getClass().getAnnotation(WxHandler.class);
    Assert.assertArgumentNotNull(anno, "anno");

    // 构造微信消息处理规则
    final WxMessageRouterRule rule = router.rule();
    rule.async(anno.async());
    if (StringUtils.isNotBlank(anno.value())) {
      rule.event(anno.value());
    }
    if (StringUtils.isNotBlank(anno.msgType())) {
      rule.msgType(anno.msgType());
    }
    if (StringUtils.isNotBlank(anno.infoType())) {
      rule.infoType(anno.infoType());
    }
    rule.handler(handler).priority(anno.priority()).accountType(anno.accountType());
    if (anno.end()) {
      rule.end();
    } else {
      rule.next();
    }
  }

}
